package cn.linstudy.product.service.impl;

import cn.linstudy.common.constant.enums.product.ProductAttrTypeEnum;
import cn.linstudy.common.utils.PageUtils;
import cn.linstudy.common.utils.Query;
import cn.linstudy.product.dao.AttrAttrgroupRelationDao;
import cn.linstudy.product.dao.AttrGroupDao;
import cn.linstudy.product.dao.CategoryDao;
import cn.linstudy.product.entity.*;
import cn.linstudy.product.service.CategoryService;
import cn.linstudy.product.vo.AttrGroupRelationVo;
import cn.linstudy.product.vo.AttrRespVo;
import cn.linstudy.product.vo.AttrVo;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cn.linstudy.product.dao.AttrDao;
import cn.linstudy.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Autowired
    AttrGroupDao attrGroupDao;

    @Autowired
    CategoryDao categoryDao;

    @Autowired
    CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveAttr(AttrVo attrVo) {
        // 这是一个对应数据库的po对象
        AttrEntity attr = new AttrEntity();
        // 复制属性
        BeanUtils.copyProperties(attrVo,attr);
        // 保存基本属性
        this.save(attr);
        // 保存关联关系(如果是基本属性的话就保存，销售属性的话就不保存)
        if(attr.getAttrType() == ProductAttrTypeEnum.ATTR_TYPE_BASE.getCode()){
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrGroupId(attrVo.getAttrGroupId());
            attrAttrgroupRelationEntity.setAttrId(attr.getAttrId());
            attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
        }

    }

    @Override
    public PageUtils queryBaseAttrListPage(Map<String, Object> params, Long catalogId) {
        QueryWrapper<AttrEntity> queryWrapper =  new QueryWrapper();
        // 如果catalogId不为0表示带条件查询
        if (catalogId != 0){
            queryWrapper.eq("catelog_id",catalogId).eq("attr_type",1);
        }
        String key = (String) params.get("key");
        // 如果有查询关键字key
        if (!StringUtils.isEmpty(key)){
            queryWrapper.and((warpper)->{
                queryWrapper.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), queryWrapper);
        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> records = page.getRecords();
        List<AttrRespVo> attrRespVos = records.stream().map((attrEntity) -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attrEntity, attrRespVo);
            // 设置分类和分组的名字
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>()
                    .eq("attr_id", attrEntity.getAttrId()));

            if (attrAttrgroupRelationEntity != null && !StringUtils.isEmpty(Long.toString( attrAttrgroupRelationEntity.getAttrGroupId()))) {
                Long attrGroupId = attrAttrgroupRelationEntity.getAttrGroupId();
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrGroupId);
                if (attrGroupEntity != null && !StringUtils.isEmpty(attrGroupEntity.getAttrGroupName())) {
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
            // 设置分类信息
            if (categoryEntity != null) {
                attrRespVo.setCatelogName(categoryEntity.getName());
            }
            return attrRespVo;
        }).collect(Collectors.toList());
        pageUtils.setList(attrRespVos);
        return pageUtils;
    }

    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        AttrRespVo attrRespVo = new AttrRespVo();
        AttrEntity attrEntity = this.getById(attrId);
        BeanUtils.copyProperties(attrEntity,attrRespVo);
        // 设置分组信息
        QueryWrapper<AttrAttrgroupRelationEntity> attrEntityQueryWrapper = new QueryWrapper<>();
        attrEntityQueryWrapper.eq("attr_id",attrId);
        AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationDao.selectOne(attrEntityQueryWrapper);
        if (attrAttrgroupRelationEntity != null && !StringUtils.isEmpty(Long.toString(attrAttrgroupRelationEntity.getAttrGroupId()))){
            attrRespVo.setAttrGroupId(attrAttrgroupRelationEntity.getAttrGroupId());
            AttrGroupEntity attrAttrgroupEntity = attrGroupDao.selectById(attrAttrgroupRelationEntity.getAttrGroupId());
            if (attrAttrgroupEntity != null && !StringUtils.isEmpty(attrAttrgroupEntity.getAttrGroupName())){
                attrRespVo.setGroupName(attrAttrgroupEntity.getAttrGroupName());
            }
        }
        // 设置分类信息
        Long catalogId = attrEntity.getCatelogId();
        if (catalogId != null){
            attrRespVo.setCatelogId(catalogId);
            Long[] catalogPath = categoryService.findCatalogPath(catalogId);
            if (catalogPath != null && catalogPath.length > 0){
                attrRespVo.setCatelogPath(catalogPath);
            }
            CategoryEntity categoryEntity = categoryDao.selectById(catalogId);
            if (categoryEntity != null && !StringUtils.isEmpty(categoryEntity.getName())){
                attrRespVo.setCatelogName(categoryEntity.getName());
            }
        }

        return attrRespVo;
    }

    @Override
    @Transactional
    public void updateAttr(AttrVo attrVo) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVo,attrEntity);
        this.updateById(attrEntity);
        AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
        if (attrVo.getAttrType() == ProductAttrTypeEnum.ATTR_TYPE_SALE.getCode()){ // 如果是基本类型才需要
            // 修改关联分组
            attrAttrgroupRelationEntity.setAttrGroupId(attrVo.getAttrGroupId());
            attrAttrgroupRelationEntity.setAttrId(attrVo.getAttrId());
            // 判断是否为空
            QueryWrapper<AttrAttrgroupRelationEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("attr_id",attrVo.getAttrId());
            Long count = attrAttrgroupRelationDao.selectCount(queryWrapper);
            if (count > 0){
                // 如果查询的关联条数大于0，说明是修改
                UpdateWrapper<AttrAttrgroupRelationEntity> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("attr_id",attrVo.getAttrId());
                attrAttrgroupRelationDao.update(attrAttrgroupRelationEntity,updateWrapper);
            }else {
                // 否则是新增
                attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
            }
        }

    }

    @Override
    public PageUtils querySaleBaseAttrListPage(Map<String, Object> params, Long catalogId) {
        QueryWrapper<AttrEntity> queryWrapper =  new QueryWrapper();
        queryWrapper.eq("attr_type",0);
        // 如果catalogId不为0表示带条件查询
        if (catalogId != 0){
            queryWrapper.eq("catelog_id",catalogId);
        }
        String key = (String) params.get("key");
        // 如果有查询关键字key
        if (!StringUtils.isEmpty(key)){
            queryWrapper.and((warpper)->{
                queryWrapper.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), queryWrapper);
        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> records = page.getRecords();
        List<AttrRespVo> attrRespVos = records.stream().map((attrEntity) -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attrEntity, attrRespVo);
            // 设置分类和分组的名字
            if (attrEntity.getAttrId() != null){
                Long attrId = attrEntity.getAttrId();
                AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>()
                        .eq("attr_id", attrId));
                if (attrAttrgroupRelationEntity != null && attrAttrgroupRelationEntity.getAttrGroupId() != null) {
                    Long attrGroupId = attrAttrgroupRelationEntity.getAttrGroupId();
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrGroupId);
                    if (attrGroupEntity != null && !StringUtils.isEmpty(attrGroupEntity.getAttrGroupName())) {
                        attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                    }
                }
            }
            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
            // 设置分类信息
            if (categoryEntity != null) {
                attrRespVo.setCatelogName(categoryEntity.getName());
            }
            return attrRespVo;
        }).collect(Collectors.toList());
        pageUtils.setList(attrRespVos);
        return pageUtils;
    }

    @Override
    public List<AttrEntity> getRelationAttr(Long attrGroupId) {
        QueryWrapper<AttrAttrgroupRelationEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("attr_group_id",attrGroupId);
        List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntities = attrAttrgroupRelationDao.selectList(queryWrapper);
        if (attrAttrgroupRelationEntities != null && attrAttrgroupRelationEntities.size() > 0){
            List<Long> collect = attrAttrgroupRelationEntities.stream().map((entity) -> {
                return entity.getAttrId();
            }).collect(Collectors.toList());
            return this.listByIds(collect);
        }
            return Collections.emptyList();
    }

    @Override
    public void deleteRelation(AttrGroupRelationVo[] attrGroupRelationVos) {
        List<AttrAttrgroupRelationEntity> attrgroupRelationEntityList = Arrays.asList(attrGroupRelationVos).stream().map((entity) -> {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(entity, attrAttrgroupRelationEntity);
            return attrAttrgroupRelationEntity;
        }).collect(Collectors.toList());
        attrAttrgroupRelationDao.deleteBatchRelation(attrgroupRelationEntityList);
    }

    @Override
    public PageUtils getNoRelation(Map<String, Object> params, Long attrGroupId) {
        // 当前分组只能关联自己所属分类里面的所有属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrGroupId);
        if (attrGroupEntity != null && attrGroupEntity.getCatelogId() != null){
            Long catelogId = attrGroupEntity.getCatelogId();
            // 当前分组只能关联别的分组没有引用的属性
            QueryWrapper<AttrGroupEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("catelog_id",catelogId);
            List<AttrGroupEntity> attrGroupEntities = attrGroupDao.selectList(queryWrapper);
            List<Long> collect = attrGroupEntities.stream().map((item) -> {
                return item.getAttrGroupId();
            }).collect(Collectors.toList());
            // 这些分组关联的属性
            QueryWrapper<AttrAttrgroupRelationEntity> entityQueryWrapper = new QueryWrapper<>();
            entityQueryWrapper.in("attr_group_id", collect);
            List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntities = attrAttrgroupRelationDao.selectList(entityQueryWrapper);
            List<Long> attrIds = attrAttrgroupRelationEntities.stream().map((item) -> {
                return item.getAttrId();
            }).collect(Collectors.toList());
            QueryWrapper<AttrEntity> attrEntityQueryWrapper = new QueryWrapper<>();
            if (attrIds != null && attrIds.size() > 0){
                attrEntityQueryWrapper.notIn("attr_id",attrIds);
            }
            // 从当前分类的所有属性移除这些属性
            attrEntityQueryWrapper.eq("catelog_id",catelogId);
            // 只查询基本属性
            attrEntityQueryWrapper.eq("attr_type",ProductAttrTypeEnum.ATTR_TYPE_BASE.getCode());
            String key = (String) params.get("key");
            if (StringUtils.isEmpty(key)){
                attrEntityQueryWrapper.and((wrapper)->{
                    wrapper.eq("attr_id",key)
                            .or().like("attr_name",key);
                });
            }
            IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), attrEntityQueryWrapper);
            return new PageUtils(page);

        }
        return null;
    }



}